package com.realshare.bby.service.integral;

import com.realshare.bby.model.RuleGroups;
import com.realshare.frame.util.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 计算积分控制器
 * author leisure
 * email 15075107120@139.com
 * create 2018-10-29 下午 4:37
 * modify 2018-10-29 下午 4:37
 **/
@Service
public class IntegralHandler {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SQLManager sqlManager;
    @Autowired
    private IntegralClear integralClear;
    @Autowired
    private AccountSync accountSync;
    @Autowired
    private VerifyUser verifyUser;
    @Autowired
    private IntegralCalculateControl calculateControl;

    public void execute() {
        syncData();
        calculate();
    }

    public void syncData() {
        integralClear.clear(); //根据配置清理过期积分
        accountSync.sync();//同步账户，以及更新核心更改的预留手机号
    }

    private void calculate() {
        try {
            log.info("开始执行计算积分任务");
            //判断最后一次积分计算是否有异常，并且是否异常已处理，如果有异常并且未处理，则停止计算
            Integer status = sqlManager.intValue("integral.calculate.findLastErrorLog", new HashMap<String, String>());
            if (status != null && status == 0) {
                throw new Exception("最后一次计算发生异常，计算任务被迫停止，需处理后才能继续计算积分");
            }
            verifyUser.verify();//核验用户组用户
            calculateControl.calculate(); //根据规则计算积分
            handlerGroupMember();//处理有效期超限的用户
            log.info("结束执行计算积分任务");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("执行计算积分任务异常，信息为：" + e.getMessage());
        }
    }

    /**
     * 处理有效期超限的用户
     */
    private void handlerGroupMember() {
        String lastDataTime = sqlManager.selectSingle("integral.calculate.findLastDataTime", null, String.class);
        Date date = StringUtils.isNotEmpty(lastDataTime) ? DateUtils.parse(lastDataTime) : null;
        if (date != null) {
            List<RuleGroups> groups = sqlManager.lambdaQuery(RuleGroups.class).andEq("status", "1").select();
            String sql = "update rule_group_members set status=3,VERIFY_DESCRIBE='已失效（超过有效期）' " +
                    "where GROUP_ID=? and status=1 and CREATE_TIME<=?";
            for (RuleGroups group : groups) {
                if (group.getActiveTimeLimit() > 0) {
                    Date d = DateUtils.addDay(date, -group.getActiveTimeLimit());
                    SQLReady ready = new SQLReady(sql, group.getId(), DateUtils.formatLongDate(d));
                    sqlManager.executeUpdate(ready);
                }
            }
        }
    }

}
